package br.com.felipeab.dexter.bean;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;

import br.com.felipeab.dexter.bo.PersistenceService;
import br.com.felipeab.dexter.domain.ServiceOrder;
import br.com.felipeab.dexter.domain.Status;
import br.com.felipeab.dexter.domain.User;
import br.com.felipeab.dexter.faces.CrudController;
import br.com.felipeab.dexter.faces.State;
import br.com.felipeab.dexter.util.BundleHelper;

/**
 * Classe ServiceOrderBean
 * 
 * @author Felipe A. Braga <br>
 *         18/06/2012 01:41:38<br>
 * 
 */
@ViewScoped
@ManagedBean(name = "serviceOrderBean")
public class ServiceOrderBean extends CrudController<ServiceOrder> {

	private static final long serialVersionUID = 4116474945741025822L;

	private ServiceOrder domain;
	private PersistenceService persistenceService;

	private List<User> listUserSolicited;

	@PostConstruct
	public void inti() {
		setState(State.INSERT);
		getDomain().setDateSolicitation(new Date());
		// TODO Depois fazer com que seja obtido o usuário logado
		getDomain().setStatusOS(Status.WAITING);
	}

	@Override
	protected PersistenceService getPersistenceService() {
		if (persistenceService == null) {
			persistenceService = new PersistenceService();
		}
		return persistenceService;
	}

	@Override
	public ServiceOrder getDomain() {
		if (domain == null) {
			domain = new ServiceOrder();
		}
		return domain;
	}

	@Override
	public void setDomain(ServiceOrder domain) {
		this.domain = domain;
	}

	@SuppressWarnings("unchecked")
	public void solicit(ActionEvent event) {
		try {
			getDomain().setSolicitant(getDomain().getSolicited());
			getDomain().setDatePrevision(new Date());
			this.getPersistenceService().save(getDomain());
			msgInfo(BundleHelper.getMessage("msg.info.sucess.requestedSO"));
		} catch (Exception e) {
			e.printStackTrace();
			msgError(BundleHelper.getMessage("msg.error.requestingSO"));
		}
	}

	public List<User> getListUserSolicited() {
		if (listUserSolicited == null) {
			this.loadListUserSolicited();
		}
		return listUserSolicited;
	}

	@SuppressWarnings("unchecked")
	public void loadListUserSolicited() {
		listUserSolicited = this.getPersistenceService().findAll(User.class);
	}

}
